package com.philosophy.web.listener;

import com.philosophy.web.domain.generate.UrlMapping;
import com.philosophy.web.event.VisitEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author philosophy
 */
@Component
@Slf4j
public class StatisticsListener {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 仅仅统计访问次数，存储到redis
     */
    @EventListener
    @Async("taskPool")
    public void statisticsVisit(VisitEvent visitEvent) {
        log.info("=============统计数据开始!");
        UrlMapping urlMapping = visitEvent.getEventSource();
        String shortUrl = urlMapping.getShortUrl();
        if (!StringUtils.hasText(shortUrl)) {
            return;
        }
        String keyFormat = "sta:%s";
        redisTemplate.opsForValue().increment(String.format(keyFormat, shortUrl));
        log.info("=============统计数据结束!");
    }
}
